
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:developer' as developer;




myLog(String str) {
  if (kDebugMode) {
    final now = DateTime.now(); // 获取当前时间
    final timeStr = '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')} '
        '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')} '
        '${now.millisecondsSinceEpoch.toString().padLeft(3, '0')}'; // 添加毫秒
    developer.log("博客项目 [$timeStr]-->$str");
  }
}

hideKeyboard(){
  FocusManager.instance.primaryFocus?.unfocus();
}


// 获取状态栏高度
double statusBarHeight(BuildContext context) {
  return MediaQuery.of(context).padding.top;
}

// 获取导航栏高度
double navigationBarHeight(BuildContext context) {
  if (Platform.isIOS) {
    return statusBarHeight(context) + 44;
  } else {
    return statusBarHeight(context) + 48;
  }
}






class IMUtils {
  IMUtils._();

 static String you  = "你";
  static String revokeMsg = "撤回了一条消息";
  static String aRevokeBMsg = "%s 撤回了 %s 的消息";


  static int MESSAGE_REVOKE_INTERVAL = 2 * 60;

  static  int MaxReEditMessageDelay = 2 * 60;

  static String IMImagePath = "assets/IM";

  static Color c_0089FF = const Color(0xFF0089FF); // 主题色
  static Color c_8E9AB0 = const Color(0xFF8E9AB0); // 说明文字
  static TextStyle ts_FF000000_15sp = TextStyle(
    color: Color(0xFF000000),
    fontSize: 15.sp,
  );

  static TextStyle ts_0089FF_12sp = TextStyle(
    color: c_0089FF,
    fontSize: 12.sp,
  );

  static  TextStyle ts_8E9AB0_12sp = TextStyle(
    color: c_8E9AB0,
    fontSize: 12.sp,
  );


  static String getSuffix(String url) {
    if (!url.contains(".")) return "";
    return url.substring(url.lastIndexOf('.'), url.length);
  }

  static bool isGif(String url) {
    return IMUtils.getSuffix(url).contains("gif");
  }

  static String? emptyStrToNull(String? str) => (null != str && str.trim().isEmpty) ? null : str;

  static bool isNotNullEmptyStr(String? str) => null != str && "" != str.trim();

  ///  判断某个数据是否为空
  static  bool  isEmpty(dynamic  input) {
    if  (input ==  null)  return  true;
    if  (input  is  String  || input  is  List  || input  is  Map) {
      return  input.isEmpty;
    }
    return  false;
  }



  static bool isUrlAddress(String url) {
    // 正则表达式
    final urlRegex = RegExp(
        r"\bhttps?://[a-zA-Z0-9\-.]+(?::(\d+))?(?:(?:/[a-zA-Z0-9\-._?,'+\&%$=~*!():@\\]*)+)?"
    );
    return urlRegex.hasMatch(url);
  }






  static deleteEmojiReplyText(TextEditingController _textController){
    // 删除逻辑，不使用_isDeleting标记
    final text = _textController.text;
    final selection = _textController.selection;

    // 正则表达式匹配 [表情] 格式的文本
    final RegExp emojiRegex = RegExp(r'\[[^\[\]]+\]');
    final matches = emojiRegex.allMatches(text).toList();

    if (matches.isNotEmpty) {
      final lastMatch = matches.last;
      if (selection.baseOffset >= lastMatch.start &&
          selection.baseOffset <= lastMatch.end) {
        // 如果光标在表情范围内，删除整个表情
        final newText = text.replaceRange(lastMatch.start, lastMatch.end, '');
        _textController.value = TextEditingValue(
          text: newText,
          selection: TextSelection.collapsed(offset: lastMatch.start),
        );
      } else {
        // 否则删除一个普通字符
        final start = selection.baseOffset > 0 ? selection.baseOffset - 1 : 0;
        final end = selection.baseOffset;
        final newText = text.replaceRange(start, end, '');
        _textController.value = TextEditingValue(
          text: newText,
          selection: TextSelection.collapsed(offset: start),
        );
      }
    }
  }




  static String _combTime(int value, String unit) => value > 0 ? '$value$unit' : '';
  static String mutedTime(int mss) {
    int days = mss ~/ (60 * 60 * 24);
    int hours = (mss % (60 * 60 * 24)) ~/ (60 * 60);
    int minutes = (mss % (60 * 60)) ~/ 60;
    int seconds = mss % 60;
    return "${_combTime(days, '天')}${_combTime(hours, '时')}${_combTime(minutes, '分')}${_combTime(seconds, '秒')}";
  }

  static String getAtNickname(String atUserID, String atNickname) {
    return atUserID == 'atAllTag' ? "每个人" : atNickname;
  }






  static String seconds2HMS(int seconds) {
    int h = 0;
    int m = 0;
    int s = 0;
    int temp = seconds % 3600;
    if (seconds > 3600) {
      h = seconds ~/ 3600;
      if (temp != 0) {
        if (temp > 60) {
          m = temp ~/ 60;
          if (temp % 60 != 0) {
            s = temp % 60;
          }
        } else {
          s = temp;
        }
      }
    } else {
      m = seconds ~/ 60;
      if (seconds % 60 != 0) {
        s = seconds % 60;
      }
    }
    if (h == 0) {
      return '${m < 10 ? '0$m' : m}:${s < 10 ? '0$s' : s}';
    }
    return "${h < 10 ? '0$h' : h}:${m < 10 ? '0$m' : m}:${s < 10 ? '0$s' : s}";
  }

  static String getUUID() {
    final timestamp = DateTime.now().millisecondsSinceEpoch;
    return "${timestamp}_${timestamp % 1000}";
  }


  static Future<T?> wrap<T>({
    required Future<T> Function() asyncFunction,
  }) async {
    T data;
    try {
      data = await asyncFunction();
    } on Exception catch (e,s) {
      //rethrow ;
      return null;
    } finally {
    }
    return data;
  }











  /// 手机号脱敏，显示前3后4，中间4位用*
  /// @param mobile 原手机号
  /// @return 脱敏后的手机号
  static String maskMobile(String? mobile) {
    if (mobile == null || mobile.length < 7) return mobile ?? '';
    return mobile.replaceRange(3, 7, '****');
  }


  /// 邮箱脱敏，第二个字符到@之间全部用*
  /// @param email 原邮箱
  /// @return 脱敏后的邮箱
  static String maskEmail(String? email) {
    if (email == null || !email.contains('@') || email.length < 3) return email ?? '';
    final atIdx = email.indexOf('@');
    if (atIdx <= 1) return email; // 只有1个字符前缀不处理
    final prefix = email.substring(0, 1);
    final stars = '*' * (atIdx - 1);
    final domain = email.substring(atIdx);
    return '$prefix$stars$domain';
  }



  static int getTimeDifferenceInSeconds(int? timestamp) {
    if(timestamp ==null)return 0;
    final now = DateTime.now();
    final messageTime = DateTime.fromMillisecondsSinceEpoch(timestamp);
    final difference = now.difference(messageTime).inSeconds;
    return difference;
  }



  static DateTime getDateTimeByMs(int ms, {bool isUtc = false}) {
    return DateTime.fromMillisecondsSinceEpoch(ms, isUtc: isUtc);
  }





}